package tree.leetcode_106_medium;

import java.util.HashMap;
import java.util.Map;

public class BuildTreeByPos {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < postorder.length; i++) {
            map.put(inorder[i], i);
        }
        return helper(map, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    public TreeNode helper(Map<Integer, Integer> map, int inLeft, int inRight, int[] postorder, int postLeft, int postRight) {
        if (inLeft > inRight || postLeft > postRight) {
            return null;
        }
        int rootVal = postorder[postRight];
        TreeNode root = new TreeNode(rootVal);
        int inRootIndex = map.get(rootVal);
        root.left = helper(map, inLeft, inRootIndex - 1, postorder, postLeft, postLeft + inRootIndex - 1 - inLeft);
        root.right = helper(map, inRootIndex + 1, inRight, postorder, postLeft + inRootIndex - inLeft, postRight - 1);
        return root;
    }
}
